package org.cxn.tools.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.Properties;


public final class PropertiesTool {
	private static final Logger logger = LoggerFactory .getLogger(PropertiesTool.class);
	private String configFile = "config.properties";
	private Properties props = null;

    public void setConfigFile(String configFile) {
        this.configFile = configFile;
        loadConfig();
    }

    private PropertiesTool() {
	}

    private static class SingltonHolder{
        private static PropertiesTool instance = new PropertiesTool();
    }

	/**
	 * 单例模式
	 * @return
	 */
	public static PropertiesTool singlton() {
		return SingltonHolder.instance;
	}


	public String getProperty(String propertyName) {

		if (props == null) {
			loadConfig();
		}
		try {
			return props.getProperty(propertyName);
		} catch (Exception e) {
			logger.error("get property value by " + propertyName
					+ " property name error:" + e.getMessage());
			return null;
		}

	}
	public Integer getPropertyToInt(String propertyName) {

		if (props == null) {
			loadConfig();
		}
		try {
			return Integer.parseInt(props.getProperty(propertyName));
		} catch (Exception e) {
			logger.error("get property value by " + propertyName
					+ " property name error:" + e.getMessage());
			return 0;
		}

	}


	private void loadConfig() {
		try {
			logger.info("load config property file :" + configFile);
			InputStream in = PropertiesTool.class.getClassLoader()
					.getResourceAsStream(configFile);
			props = new Properties();
			props.load(in);
		} catch (Exception e) {
			logger.error("load config property file error:" + e.getMessage());
		}
	}
}